<template>
  <FIPanel class="page-tree" :usePadding="false">
    <div class="page-tree__title">流程目录树</div>
    <div class="page-tree__line"></div>
    <el-input
      class="page-tree__search"
      v-model="filterText"
      :prefix-icon="Search"
      style="width: 250px"
      placeholder="请输入"
    />
    <el-tree
      ref="treeRef"
      style="max-width: 600px"
      :data="state.treeData"
      :props="defaultProps"
      :highlight-current="true"
      :current-node-key="curryNodeKey"
      @node-click="handleNodeClick"
      lazy
      :load="loadNode"
      :filter-node-method="filterNode"
      @current-change="onCurrentNodeChange"
    >
      <template #default="{ node }">
        <div
          class="custom-tree-node"
          :class="[{ 'custom-tree-node3': node.level === 3 }, { 'custom-tree-node4': node.level === 4 }]"
        >
          <span class="custom-tree-node-label common-text-ellipsis"> {{ node.label }}</span>
          <el-dropdown v-if="selectedNode.label === node.label" class="custom-tree-node-add" trigger="click">
            <i class="font_family icon-xinzeng"></i>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleOperate('insert', node)">新增 </el-dropdown-item>
                <el-dropdown-item @click="handleOperate('update', node)">编辑</el-dropdown-item>
                <el-dropdown-item @click="handleOperate('delete', node)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template></el-tree
    >
  </FIPanel>
  <!-- <CategoryModel :visible="visibleModel" @close="visibleModel = false" /> -->

  <CategoryModel
    :visible="visibleModel"
    :type="nodeState.operateMode"
    :info="selectedNode"
    @update:visible="(newValue) => (visibleModel = newValue)"
    @save-ok="handleSave"
  />
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FIPanel from '@/components/FIPanel.vue'
import CategoryModel from './CategoryModel.vue'
import FIModel from '@/components/FIModel.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElTree } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useMessage, useMessageBox } from '@/hooks/message'

const state = reactive({
  treeData: [],
})
interface Tree {
  appCname: string
  leaf?: boolean
  loading?: boolean // 添加此行
}
const emits = defineEmits(['node-click', 'node-change'])
const curryNodeKey = ref('')
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const isVisible = ref(false)
const ruleFormRef1 = ref(null)
const optionsArr = ref([])
const selNode = ref([])
const handleNodeClick = (data: Tree) => {
  selNode.value = data

  emits('node-click', data)
  console.log('data11111-------', data)
  curryNodeKey.value = data.id
}
const ruleForm1 = ref({
  moduleEname1: [],
})
const rules1 = reactive({
  moduleEname1: [{ required: true, message: '请选择一级模块', trigger: 'change' }],
})

const defaultProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'leaf',
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const selectedNode = ref({})
const selectedNodeObj = ref({})

const onCurrentNodeChange = (e, nodeData) => {
  infoFormType.value = 'info'
  selectedNode.value = e
  selectedNodeObj.value = nodeData
  infoFormLevel.value = nodeData.level
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
  // if (node.level === 0) {
  //   return resolve([{ label: '流程目录' }])
  // }
  // 获取项目模块
  try {
    console.log('node----------', node)
    apiRequestPost('/bpm-service/BpmCategory/query', {
      categoryId: node?.data?.id,
      isRoot: node.level == 0 ? true : false,
    })
      .then((res) => {
        if (res.data.success) {
          Array.isArray(res.data.data) &&
            res.data.data.forEach((item) => {
              // item.label = item.appCname
              item.label = item.name
              item.leaf = false
              item.children = null
            })
          const loadedNodes = res.data.data.map((item) => ({
            ...item,
            // 若有子节点，则不是叶子节点，不设置isLeaf；若无子节点，则是叶子节点
            isLeaf: false,
            loading: false,
          }))

          resolve(loadedNodes)
          // if (selNode.value) {
          //   treeRef.value?.setCurrentKey(selNode.value.nodeId)
          // }
        } else {
          resolve([])
        }
      })
      .catch((error: any) => {
        // 处理错误
        resolve([])
      })
  } catch (error) {
    resolve([])
  }
}
const infoFormTitle = ref('')
const infoFormType = ref('info')
const infoFormLevel = ref(1)

const refreshTreeNode = () => {
  console.log(selectedNodeObj, 'selectedNodeObj')
  useMessage().success('更新成功')
  let parentId = selectedNodeObj.value?.parent?.id
  console.log(parentId, 'parentId')
  let node = treeRef.value.getNode(parentId)
  if (node) {
    setTimeout(() => {
      node.loaded = false
      node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
    }, 1000)
    // 刷新完成后，重新选中当前节点（如果它仍然存在）
    const refreshedCurrentNode = treeRef.value.getNode(currentlySelectedNode.id)
    if (refreshedCurrentNode) {
      treeRef.value.setCurrentKey(refreshedCurrentNode.key) // 选中当前节点
    } else {
      // 如果当前节点不存在（可能已被移除），则尝试选中其父节点
      treeRef.value.setCurrentKey(node.key) // 选中父节点
    }
  }
}
const visibleModel = ref(false)
const nodeState = reactive({
  operateMode: '',
  key: '',
  name: '',
  parentId: '',
  desc: '',
})
const handleOperate = (type, nodeData) => {
  if (type === 'delete') {
    console.log('nodeData------', nodeData)
    useMessageBox()
      .confirm('是否确认删除该目录？', '提示')
      .then(() => {
        apiRequestPost('/bpm-service/BpmCategory/deleteCategory', {
          categoryId: nodeData.data.id,
        }).then((res) => {
          if (res.data.success) {
            useMessage().success('删除成功')
            refreshTreeNode()
          } else {
            useMessage().error(res.message)
          }
        })
      })
      .catch(() => {})
  } else {
    visibleModel.value = true
    nodeState.operateMode = type
  }
  // let apiUrl = ''
  // if (type == 'delete') apiUrl = '/bpm-service/BpmCategory/deleteCategory'
  // else apiUrl = '/bpm-service/BpmCategory/saveCategoryInfo'
  // if (type == 'insert') {
  //   apiRequestPost(apiUrl, nodeState).then((res) => {})
  // }
}
const handleSave = (data) => {
  refreshTreeNode()
}
onMounted(() => {
  // getTreeData('0', {})
  // getAllModule1Data()
})
</script>
<style lang="less" scoped>
.page-tree {
  // width: 228px;
  width: 280px;
  min-height: calc(100vh - 175px);
  padding: 16px;
  .page-tree__title {
    font-size: 16px;
    color: #303133;
    line-height: 28px;
    text-align: left;
    font-weight: bold;
  }
  .page-tree__line {
    margin: 16px -16px;
    height: 1px;
    background: #e8e8e8;
    width: calc(100% + 32px);
  }
  .page-tree__search {
    margin-bottom: 18px;
  }
  .custom-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // width: 100%;
    width: calc(100% - 26px);
    height: 32px;
    padding-right: 5px;
    position: relative;
    &-label {
      width: calc(100% - 20px);
      // width: 100%;
      text-align: left;
      // padding-right: 60px;
    }
    // &-label3 {
    //   width: calc(100% - 50px);
    //   // width: 100%;
    //   text-align: left;
    //   // padding-right: 60px;
    // }
    // &-label4 {
    //   width: calc(100% - 70px);
    //   // width: 100%;
    //   text-align: left;
    //   // padding-right: 60px;
    // }
    &-add {
      position: absolute;
      right: 5px;
      top: 8px;
      color: var(--el-color-primary-light-2);
    }
  }
  .custom-tree-node3 {
    width: calc(100% - 30px);
  }
  .custom-tree-node4 {
    width: calc(100% - 30px);
  }
  ::v-deep(.el-tree-node__content) {
    height: 32px;
    border-radius: 2px;
    .el-tree-node__expand-icon {
      color: #989898;
    }
  }
}

::v-deep(.el-dropdown-menu__item) {
  padding: 5px 16px;
  border-radius: 2px;
  margin: 4px;
}
</style>
